<template>
	<view class="page">
		<!-- 头部导航 -->
		<view class="header-bag">
			<image src="/static/icon-Get-into@3.png" class="back" @click="goBack"></image>
			<text class="page-title">填写生活商家信息</text>
		</view>

		<view class="wrapper">
			<!-- 门店牌匾照片 -->
			<view class="id-card">
				<view class="card-title">
					<text class="required">*</text>
					<text>门店牌匾照片</text>
				</view>
				<view class="photo-container">
					<view class="photo-box" @click="selectPhoto('shopp')">
						<image class="photo-img" :src="shopPhoto || '/static/icon-photo1（tianxieshangjia）@2x.png'"></image>
					</view>
				</view>
			</view>

			<!-- 店内环境照片 -->
			<view class="id-card">
				<view class="card-title">
					<text class="required">*</text>
					<text>店内环境照片<text class="sub-text">(最多两张)</text></text>
				</view>
				<view class="photo-container env-photos">
					<view v-for="(photo, index) in envPhotos" :key="index" class="photo-box env-photo">
						<image class="photo-img" :src="photo"></image>
						<image class="del-img" src="/static/icon-guanbi@3x.png" @click="deleteEnvPhoto(index)"></image>
					</view>
					<view v-if="envPhotos.length < 2" class="photo-box" @click="selectPhoto('showEnviro')">
						<image class="photo-img" src="/static/icon-photo1（tianxieshangjia）@2x.png"></image>
					</view>
				</view>
			</view>

			<!-- 法人手持身份证拍照 -->
			<view class="id-card">
				<view class="card-title">
					<text class="required">*</text>
					<text>法人手持身份证拍照</text>
				</view>
				<view class="photo-container id-photos">
					<view class="photo-box" @click="selectPhoto('idFront')">
						<image class="photo-img" :src="idFrontPhoto || '/static/icon-sfz(zheng)@2x.png'"></image>
						<text class="photo-label">身份证正面</text>
					</view>
					<view class="photo-box" @click="selectPhoto('idBack')">
						<image class="photo-img" :src="idBackPhoto || '/static/icon-sfz(fan)@2x.png'"></image>
						<text class="photo-label">身份证反面</text>
					</view>
				</view>
			</view>

			<!-- 营业执照 -->
			<view class="id-card">
				<view class="card-title">
					<text class="required">*</text>
					<text>营业执照</text>
				</view>
				<view class="photo-container">
					<view class="photo-box" @click="selectPhoto('permission')">
						<image class="photo-img" :src="permissionPhoto || '/static/permission1.png'"></image>
					</view>
				</view>
			</view>

			<!-- 其他相关证件 -->
			<view class="id-card">
				<view class="card-title">
					<text>其他相关证件</text>
				</view>
				<view class="xukezheng">如餐饮服务许可证、食品流通许可证等</view>
				<view class="other-photos">
					<view v-for="(photo, index) in otherPhotos" :key="index" class="other-photo-item">
						<image class="photo-img" :src="photo"></image>
						<image class="close-btn" src="/static/sctp@2x.png" @click="deleteOtherPhoto(index)"></image>
					</view>
					<view v-if="otherPhotos.length < 6" class="photo-box other-add" @click="selectPhoto('foodPermit')">
						<image class="photo-img" src="/static/sctp_six@2x.png"></image>
					</view>
				</view>
			</view>

			<!-- 商标图 -->
			<view class="id-card">
				<view class="card-title">
					<text class="required">*</text>
					<text>商标图</text>
				</view>
				<view class="photo-container">
					<view class="photo-box" @click="selectPhoto('tradesMarkP')">
						<image class="photo-img" :src="tradeMarkPhoto || '/static/icon-photo1（tianxieshangjia）@2x.png'"></image>
					</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-btn" @click="submitForm">提交</view>
		</view>
	</view>
</template>

<script>
	import { merchantApi } from '@/api/index.js'
	
	export default {
		data() {
			return {
				// 照片数据
				shopPhoto: '', // 门店牌匾照片
				envPhotos: [], // 店内环境照片
				idFrontPhoto: '', // 身份证正面
				idBackPhoto: '', // 身份证反面
				permissionPhoto: '', // 营业执照
				otherPhotos: [], // 其他证件照片
				tradeMarkPhoto: '', // 商标图
				
				// 当前选择的照片类型
				currentPhotoType: '',
				
				// 申请ID（修改时使用）
				applyId: ''
			}
		},
		
		onLoad(options) {
			if (options.id) {
				this.applyId = options.id
				this.loadApplyData()
			}
		},
		
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},
			
			// 加载申请数据（修改时使用）
			async loadApplyData() {
				try {
					const res = await merchantApi.getApplyList({ id: this.applyId })
					if (res.r === 0 && res.data.aplist) {
						this.parseApplyData(res.data.aplist)
					}
				} catch (error) {
					console.error('加载申请数据失败:', error)
				}
			},
			
			// 解析申请数据
			parseApplyData(aplist) {
				aplist.forEach(item => {
					if (item.imgs) {
						item.imgs.forEach(img => {
							const fullUrl = this.getFullImageUrl(img.file_path)
							switch (img.img_type) {
								case 6: // 身份证正面
									this.idFrontPhoto = fullUrl
									break
								case 7: // 身份证反面
									this.idBackPhoto = fullUrl
									break
								case 8: // 店铺牌匾
									this.shopPhoto = fullUrl
									break
								case 9: // 店铺内环境
									this.envPhotos.push(fullUrl)
									break
								case 10: // 营业执照
									this.permissionPhoto = fullUrl
									break
								case 11: // 餐饮服务许可证
									this.otherPhotos.push(fullUrl)
									break
								case 12: // 商标
									this.tradeMarkPhoto = fullUrl
									break
							}
						})
					}
				})
			},
			
			// 获取完整图片URL
			getFullImageUrl(path) {
				if (!path) return ''
				// 使用API配置中的图片URL前缀
				return path.startsWith('http') ? path : `http://static.youpin91.com${path}`
			},
			
			// 选择照片
			selectPhoto(type) {
				this.currentPhotoType = type
				
				uni.chooseImage({
					count: type === 'showEnviro' ? 2 - this.envPhotos.length : 
						   type === 'foodPermit' ? 6 - this.otherPhotos.length : 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						this.handleImageSelect(res.tempFilePaths)
					}
				})
			},
			
			// 处理图片选择
			async handleImageSelect(filePaths) {
				for (let filePath of filePaths) {
					try {
						const uploadRes = await this.uploadImage(filePath)
						if (uploadRes.r === 0) {
							this.setPhotoByType(uploadRes.data.file_path[0])
						}
					} catch (error) {
						console.error('上传图片失败:', error)
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						})
					}
				}
			},
			
			// 根据类型设置照片
			setPhotoByType(imagePath) {
				const fullUrl = this.getFullImageUrl(imagePath)
				
				switch (this.currentPhotoType) {
					case 'shopp':
						this.shopPhoto = fullUrl
						break
					case 'showEnviro':
						if (this.envPhotos.length < 2) {
							this.envPhotos.push(fullUrl)
						}
						break
					case 'idFront':
						this.idFrontPhoto = fullUrl
						break
					case 'idBack':
						this.idBackPhoto = fullUrl
						break
					case 'permission':
						this.permissionPhoto = fullUrl
						break
					case 'foodPermit':
						if (this.otherPhotos.length < 6) {
							this.otherPhotos.push(fullUrl)
						}
						break
					case 'tradesMarkP':
						this.tradeMarkPhoto = fullUrl
						break
				}
			},
			
			// 上传图片
			async uploadImage(filePath) {
				try {
					const imagePath = await merchantApi.uploadImage(filePath)
					return { r: 0, data: { file_path: [imagePath] } }
				} catch (error) {
					console.error('上传图片失败:', error)
					throw error
				}
			},
			
			// 删除环境照片
			deleteEnvPhoto(index) {
				this.envPhotos.splice(index, 1)
			},
			
			// 删除其他证件照片
			deleteOtherPhoto(index) {
				this.otherPhotos.splice(index, 1)
			},
			
			// 表单验证
			validateForm() {
				if (!this.shopPhoto) {
					uni.showToast({ title: '请上传门店牌匾照片', icon: 'none' })
					return false
				}
				if (this.envPhotos.length === 0) {
					uni.showToast({ title: '请上传店铺内环境照片', icon: 'none' })
					return false
				}
				if (!this.idFrontPhoto) {
					uni.showToast({ title: '请上传身份证正面照', icon: 'none' })
					return false
				}
				if (!this.idBackPhoto) {
					uni.showToast({ title: '请上传身份证背面照', icon: 'none' })
					return false
				}
				if (!this.permissionPhoto) {
					uni.showToast({ title: '请上传营业执照', icon: 'none' })
					return false
				}
				if (!this.tradeMarkPhoto) {
					uni.showToast({ title: '请上传商标', icon: 'none' })
					return false
				}
				return true
			},
			
			// 提交表单
			async submitForm() {
				if (!this.validateForm()) return
				
				try {
					const businessInfo = uni.getStorageSync('bussinessInfor')
					if (!businessInfo) {
						uni.showToast({ title: '请先填写商家基本信息', icon: 'none' })
						return
					}
					
					const submitData = {
						...businessInfo.page1,
						...businessInfo.page2,
						cfi_path: this.getImagePath(this.idFrontPhoto),
						cbi_path: this.getImagePath(this.idBackPhoto),
						spi_path: this.getImagePath(this.shopPhoto),
						sii_paths: this.envPhotos.map(url => this.getImagePath(url)).join(';'),
						bli_path: this.getImagePath(this.permissionPhoto),
						csli_path: this.otherPhotos.map(url => this.getImagePath(url)).join(';'),
						ti_path: this.getImagePath(this.tradeMarkPhoto)
					}
					
					let res
					if (this.applyId) {
						// 更新申请
						res = await merchantApi.updateBusinessApply({
							id: this.applyId,
							...submitData
						})
					} else {
						// 新增申请
						res = await merchantApi.addBusinessApply(submitData)
					}
					
					if (res.r === 0) {
						uni.showToast({ title: '提交成功', icon: 'success' })
						setTimeout(() => {
							uni.navigateBack({ delta: 3 })
						}, 1500)
					} else {
						uni.showToast({ title: res.msg || '提交失败', icon: 'none' })
					}
				} catch (error) {
					console.error('提交失败:', error)
					uni.showToast({ title: '提交失败', icon: 'none' })
				}
			},
			
			// 获取图片路径（去掉域名前缀）
			getImagePath(fullUrl) {
				if (!fullUrl) return ''
				return fullUrl.replace(/^https?:\/\/[^\/]+/, '')
			}
		}
	}
</script>

<style scoped>
	.page {
		background-color: #eeeeee;
		min-height: 100vh;
	}
	
	.header-bag {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 88rpx;
		background-color: #fff;
		border-bottom: 1px solid #e3e3e3;
		position: relative;
	}
	
	.back {
		position: absolute;
		left: 30rpx;
		width: 40rpx;
		height: 40rpx;
	}
	
	.page-title {
		font-size: 36rpx;
		color: #333;
	}
	
	.wrapper {
		padding-bottom: 40rpx;
	}
	
	.id-card {
		background-color: #ffffff;
		margin-top: 20rpx;
		padding: 30rpx;
	}
	
	.card-title {
		font-size: 30rpx;
		margin-bottom: 30rpx;
	}
	
	.required {
		color: #ff2e00;
		margin-right: 10rpx;
	}
	
	.sub-text {
		color: #999;
		font-size: 26rpx;
	}
	
	.photo-container {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}
	
	.photo-box {
		position: relative;
		width: 218rpx;
		height: 192rpx;
		border-radius: 8rpx;
		overflow: hidden;
	}
	
	.photo-img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}
	
	.photo-label {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.5);
		color: #fff;
		text-align: center;
		font-size: 24rpx;
		padding: 10rpx 0;
	}
	
	.env-photos {
		position: relative;
	}
	
	.env-photo {
		position: relative;
	}
	
	.del-img {
		position: absolute;
		top: 0;
		right: 0;
		width: 30rpx;
		height: 30rpx;
		z-index: 10;
	}
	
	.id-photos {
		gap: 40rpx;
	}
	
	.xukezheng {
		font-size: 24rpx;
		color: #6e6e6e;
		margin-bottom: 30rpx;
	}
	
	.other-photos {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
	}
	
	.other-photo-item {
		position: relative;
		width: 218rpx;
		height: 192rpx;
	}
	
	.close-btn {
		position: absolute;
		top: 0;
		right: 0;
		width: 30rpx;
		height: 30rpx;
		z-index: 10;
	}
	
	.other-add {
		width: 218rpx;
		height: 192rpx;
	}
	
	.submit-btn {
		height: 90rpx;
		width: 689rpx;
		line-height: 90rpx;
		text-align: center;
		background: #11b445;
		color: white;
		margin: 20rpx auto;
		border-radius: 20rpx;
		font-size: 34rpx;
	}
</style>